﻿#region  Copyright (C) 2013 Unisys Corporation

// =============================================================================================
// All Rights Reserved. This work contains trade secrets and confidential material of UNISYS, 
// and its use or disclosure in whole or in part without explicit written permission of 
// UNISYS is prohibited. 
//  
// Product Name          :  Unisys e-Workflow and Imaging
// File Name             :  fSplashScreen.cs
// Authored By           :  Unisys Corporation
// =============================================================================================
//	Modified by                         Date            Version
// =============================================================================================
//	ronald.aguilar@cr.unisys.com      Jun 06, 2013    Initial Version
// =============================================================================================
#endregion

#region Using Region
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using Unisys.DuplicateCheck.Data;
using Unisys.DuplicateCheck.Data.Logger;
using Unisys.DuplicateCheck.Data.DataBase;
using Unisys.DuplicateCheck.Entity;
using Unisys.DuplicateCheck.Logic;
using Unisys.DuplicateCheck.Logic.Services;
using System.Configuration;
#endregion

namespace TestSplashScreen
{

    public partial class fSplashScreen : Form
    {
        const int DEFAULT_TIME = 1000;
        bool Continue = true;
        Thread t;

       public fSplashScreen()
        {
            InitializeComponent();
            this.Shown += new EventHandler(fSplashScreen_Shown);
            this.FormClosing += new FormClosingEventHandler(Form1_FormClosing);
            this.closeButton.Click += new EventHandler(closeButton_Click);
        }

       void closeButton_Click(object sender, EventArgs e)
       {
           this.DialogResult = System.Windows.Forms.DialogResult.Cancel;
           this.Close();
       }

        void fSplashScreen_Shown(object sender, EventArgs e)
        {
            initvalues();
            t = new System.Threading.Thread(initApplication);
            t.Start();
        }

        void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (t != null && t.IsAlive)
            {
                t.Abort();
                t = null;
            }
        }

        private void initvalues()
        {
            titleLabel.Text = String.Format("{0} v1.0", Application.ProductName);
            messageLabel.Text = "Inicializando...";

            
        }

        public void initApplication()
        {
            Thread.Sleep(DEFAULT_TIME);
            this.Invoke((MethodInvoker)(() => setMessage("Cargando configuración...")));

            #region Load Configuration
            try
            {
                Configuration.Load();

                if (!(verifyConfiguration()))
                {
                    Logger.LogThis4Windows("Error al intentar leer la configuracion de la aplicacion. La verificacion de la configuracion" +
                    " no ha finalizado con exito, favor revise la configuracion", "Unisys Duplicate Check App", "Unisys Duplicate Check Application");
                    System.Environment.Exit(0);
                }
            }
            catch (Exception exc)
            {
                Logger.LogThis4Windows("Error al intentar leer la configuracion de la aplicacion " + exc.Message, "Unisys Duplicate Check App", "Unisys Duplicate Check Application");
                System.Environment.Exit(0);
            }
            Service.sendLog("La aplicación ha cargado su configuración correctamente.", Service.errorType.Information_Message);


            #endregion

            Thread.Sleep(DEFAULT_TIME);
            this.Invoke((MethodInvoker)(() => setMessage("Conectando a la base de datos...")));

            Thread.Sleep(DEFAULT_TIME);
            this.Invoke((MethodInvoker)(() => setMessage("Verificando directorios de Logs...")));

            
            Thread.Sleep(DEFAULT_TIME);
            this.Invoke((MethodInvoker)(() => setMessage("Iniciando aplicación...")));

            Thread.Sleep(DEFAULT_TIME);
            if (this.InvokeRequired) this.Invoke(new Action(finishProcess));
        }

        public void setMessage(string msg)
        {
            messageLabel.Text = msg;
        }

        private void finishProcess()
        {
            this.DialogResult = System.Windows.Forms.DialogResult.OK;
            this.Close();
        }

        private bool verifyConfiguration()
        {
            #region Parameters not NULL
            if (Configuration.duplicateRules.Equals(""))
            {
                Service.sendLog("El parámetro [duplicateRules] no puede estar en blanco.", Service.errorType.Error_Message);
                return false;
            }

            if (Configuration.logLocation.Equals(""))
            {
                Service.sendLog("El parámetro [logLocation] no puede estar en blanco.", Service.errorType.Error_Message);
                return false;
            }

            if (Configuration.logMaxSizeBytes.Equals(""))
            {
                Service.sendLog("El parámetro [logMaxSizeBytes] no puede estar en blanco.", Service.errorType.Error_Message);
                return false;
            }

            if (Configuration.readCommand.Equals(""))
            {
                Service.sendLog("El parámetro [readCommand] no puede estar en blanco.", Service.errorType.Error_Message);
                return false;
            }

            if (Configuration.stringConnection.Equals(""))
            {
                Service.sendLog("El parámetro [stringConnection] no puede estar en blanco.", Service.errorType.Error_Message);
                return false;
            }

            if (Configuration.systemID.Equals(""))
            {
                Service.sendLog("El parámetro [systemID] no puede estar en blanco.", Service.errorType.Error_Message);
                return false;
            }

            if (Configuration.topQuery.Equals(""))
            {
                Service.sendLog("El parámetro [topQuery] no puede estar en blanco.", Service.errorType.Error_Message);
                return false;
            }

            if (Configuration.updateCommand.Equals(""))
            {
                Service.sendLog("El parámetro [updateCommand] no puede estar en blanco.", Service.errorType.Error_Message);
                return false;
            }
            #endregion

            if (!(verifyLogsZone()))
                return false;

            //if (!(verifyConfiguration()))
            //    return false;

            //if (!(verifyDataBaseZone()))
            //    return false;

            return true;
        }

        private bool verifyLogsZone()
        {
            try
            {
                if (!(System.IO.Directory.Exists(Configuration.logLocation)))
                    System.IO.Directory.CreateDirectory(Configuration.logLocation);

                if(Configuration.logMaxSizeBytes <= 0)
                    return false;

                return true;
            }
            catch (Exception exc)
            { 
               Logger.LogThis4Windows("Error al intentar leer la configuracion de la aplicacion " + exc.Message, "Unisys Duplicate Check App", "Unisys Duplicate Check Application");
                return false;
            }
 
        }

        private bool verifyDataBaseZone()
        {
            try
            {
                SqlDataClass dataClass = new SqlDataClass();
                dataClass.OpenConnection();
                Service.sendLog("Conexión de BD abierta con exito.", Service.errorType.Information_Message);
                dataClass.CloseConnection();
                Service.sendLog("Conexión de BD cerrada sin problemas.", Service.errorType.Information_Message);

                return true;
            }
            catch (Exception exc)
            {
                Service.sendLog("Imposible realizar la conexión con la BD.", Service.errorType.Error_Message, exc);
                return false;
            }
        }

      
    }
}
